#include "MultiVariateSorter.h"
#include <math.h>

MultiVariateSorter::MultiVariateSorter(const Dictionary & dictionary)
	: BaseSorter(dictionary)
{
}

int MultiVariateSorter::getCategoryIndexOf(const Document & document) {
	std::vector<double> sum(dictionary.getCategoriesCount());

	const WordsCountMap & wcm = document.getWordsCountMap();
	for (WordsCountMap::const_iterator iter=wcm.begin(); iter != wcm.end(); ++iter) {

		TermsMap::const_iterator dicIter = dictionary.getTermsMap().find(iter->first);
		if ((dictionary.getTermsMap().end() == dicIter) || (!dicIter->second.concerned)) {
			continue;
		}


		for (uint i = 0; i < dictionary.getCategoriesCount(); ++i) {
			if (dicIter->second.totalInCategory[i] > 0) {
				sum[i] += logTermProbInCategory(dicIter->second, i);
			} else {
				sum[i] += logTermProbNotInCategory(dicIter->second, i);
			}
		}
	}
	double max = -1.7e+300;
	int maxindex = 0;
	for (uint i = 0; i < sum.size(); ++i) {
		if (sum[i] > max) {
			max = sum[i];
			maxindex = i;
		}
	}
	return maxindex;
}

double MultiVariateSorter::logTermProbInCategory(const Term & term, int catIndex) {
	return ( log((double)term.totalInCategory[catIndex] + 1) -
		log((double)2 + dictionary.getCategory(catIndex).documentsCount) );
}

double MultiVariateSorter::logTermProbNotInCategory(const Term & term, int catIndex) {
	return ( log((double)1 + dictionary.getCategory(catIndex).documentsCount -
		term.totalInCategory[catIndex]) -
		log((double)2 + dictionary.getCategory(catIndex).documentsCount) );
}
